package org.spice.servlet.tags;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.DynamicAttributes;

public class OptionListTag extends BaseTag implements DynamicAttributes{
	

	private static 
	final long serialVersionUID = 1L;

	protected 
	String ref;
	
	protected 
	Boolean isValidation;
	
	protected
	String name;
	
	protected
	String value;
	
	public 
	String getValue() {
		return value;
	}
	
	public 
	void setValue(String value) {
		this.value = value;
	}
	
	protected
	Map<?, ?> optionValues;
	
	public 
	Map<?, ?> getOptionValues() {
		return optionValues;
	}
	
	public 
	void setOptionValues(Map<?, ?> optionValues) {
		this.optionValues = optionValues;
	}
	
	public 
	String getName() {
		return name;
	}
	
	public 
	void setName(String name) {
		this.name = name;
	}
	
	public 
	Boolean getIsValidation() {
		return isValidation;
	}
	
	public 
	void setIsValidation(Boolean isValidation) {
		this.isValidation = isValidation;
	}
	
	
	public 
	String getRef() {
		return ref;
	}
	
	public 
	void setRef(String ref) {
		this.ref = ref;
	}
	
	

	@Override
	public int doEndTag() throws JspException {
		try {
			this.pageContext.getOut().append("</select>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	@Override
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}
	

	@Override
	public 
	void setDynamicAttribute(String uri, String localName, Object value)
			throws JspException {
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public int writeTag(PageContext pageContext) {
		try {
			String reference = getRef();
			if (reference.contains(",")) {
				reference = reference.replace(" ", "");
				Enumeration<String> attributes = this.pageContext.getRequest()
						.getAttributeNames();
				List<String> enumList = Collections.list(attributes);
				for (String singleEntity : enumList) {
					if (singleEntity.trim().equalsIgnoreCase(reference.trim())) {
						
						for (Map.Entry<?, ?> entry : ((Map<?,?>) this.pageContext.getRequest().getAttribute(singleEntity.trim()))
								.entrySet()) {
							this.pageContext.getOut().append(
									"<option value = \"" + entry.getKey()
											+ "\"> \"" + entry.getValue()
											+ "\" </option>");
						}
					}
				}
				
			}
				
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return EVAL_BODY_INCLUDE;
	}

}
